package com.sun.lib;

import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.os.Build;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.ViewTreeObserver;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.sun.lib.util.TextViewUtil;

/**
 * Created by Administrator on 2019/5/7.
 * <p>
 * #                                                   #
 * #                       _oo0oo_                     #
 * #                      o8888888o                    #
 * #                      88" . "88                    #
 * #                      (| -_- |)                    #
 * #                      0\  =  /0                    #
 * #                    ___/`---'\___                  #
 * #                  .' \\|     |# '.                 #
 * #                 / \\|||  :  |||# \                #
 * #                / _||||| -:- |||||- \              #
 * #               |   | \\\  -  #/ |   |              #
 * #               | \_|  ''\---/''  |_/ |             #
 * #               \  .-\__  '-'  ___/-. /             #
 * #             ___'. .'  /--.--\  `. .'___           #
 * #          ."" '<  `.___\_<|>_/___.' >' "".         #
 * #         | | :  `- \`.;`\ _ /`;.`/ - ` : | |       #
 * #         \  \ `_.   \_ __\ /__ _/   .-` /  /       #
 * #     =====`-.____`.___ \_____/___.-`___.-'=====    #
 * #                       `=---='                     #
 * #     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~   #
 * #                                                   #
 * #               佛祖保佑         永无BUG              #
 * #                                                   #
 */
public class STextViewHelper extends SBaseHelper<TextView> {

    private static final int ICON_LEFT = 1, ICON_RIGHT = 2, ICON_TOP = 3, ICON_BOTTOM = 4;
    private int mTextColor;
    private int mTextColorSelected;
    private int mTextColorChecked;
    private int mTextColorUnable;

    private int[][] states = new int[4][];
    //icon
    private int mIconWidth;
    private int mIconHeight;
    private int mIconDirection;

    // drawable
    private Drawable mIcon = null;
    private Drawable mIconNormal;
    private Drawable mIconSelected;
    private Drawable mIconChecked;
    private Drawable mIconUnable;
    private int paddingLeft;
    private int paddingRight;
    private int paddingTop;
    private int paddingBottom;
    //icon和text位置同步
    private boolean mDrawableWithText;

    private String mCacheSingleIconPaddingVale;


    public STextViewHelper(Context context, TextView view, AttributeSet attrs) {
        super(context, view, attrs);
        initAttrbuteSet(context, attrs);
        addOnViewChangeListener();
    }

    private void addOnViewChangeListener() {
        if (mView == null) return;
        mView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                mView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                paddingLeft = mView.getPaddingLeft();
                paddingRight = mView.getPaddingRight();
                paddingTop = mView.getPaddingTop();
                paddingBottom = mView.getPaddingBottom();
                setIcon();
            }
        });

        mView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                setIcon();
            }
        });
    }

    private void initAttrbuteSet(Context context, AttributeSet attrs) {
        if (context == null || attrs == null) {
            setup();
            return;
        }
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.STextView);
        mTextColor = array.getColor(R.styleable.STextView_text_color, mView.getCurrentTextColor());
        mTextColorSelected = array.getColor(R.styleable.STextView_text_color_selected, Color.TRANSPARENT);
        mTextColorChecked = array.getColor(R.styleable.STextView_text_color_checked, Color.TRANSPARENT);
        mTextColorUnable = array.getColor(R.styleable.STextView_text_color_unable, Color.TRANSPARENT);
        //icon
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mIconNormal = array.getDrawable(R.styleable.STextView_icon_src);
            mIconSelected = array.getDrawable(R.styleable.STextView_icon_src_selected);
            mIconChecked = array.getDrawable(R.styleable.STextView_icon_src_checked);
            mIconUnable = array.getDrawable(R.styleable.STextView_icon_src_unable);
        } else {
            int normalId = array.getResourceId(R.styleable.STextView_icon_src, -1);
            int selectedId = array.getResourceId(R.styleable.STextView_icon_src_selected, -1);
            int unableId = array.getResourceId(R.styleable.STextView_icon_src_unable, -1);
            int checkedId = array.getResourceId(R.styleable.STextView_icon_src_checked, -1);
            if (normalId != -1)
                mIconNormal = context.getResources().getDrawable(normalId);
            if (selectedId != -1)
                mIconSelected = context.getResources().getDrawable(selectedId);
            if (checkedId != -1)
                mIconChecked = context.getResources().getDrawable(checkedId);
            if (unableId != -1)
                mIconUnable = context.getResources().getDrawable(unableId);
        }

        mIconWidth = array.getDimensionPixelSize(R.styleable.STextView_icon_width, 0);
        mIconHeight = array.getDimensionPixelSize(R.styleable.STextView_icon_height, 0);
        mIconDirection = array.getInt(R.styleable.STextView_icon_direction, ICON_LEFT);

        mDrawableWithText = array.getBoolean(R.styleable.STextView_icon_with_text, false);

        array.recycle();
        //  setTvup();
        setup();
    }

    private void setup() {
        if (!mView.isEnabled()) {
            mIcon = mIconUnable;
        } else if (mView.isSelected()) {
            mIcon = mIconSelected;
        } else if (isCompoundButtonChecked()) {
            mIcon = mIconChecked;
        } else {
            mIcon = mIconNormal;
        }

        states[0] = new int[]{-android.R.attr.state_enabled};
        states[1] = new int[]{android.R.attr.state_checked};
        states[2] = new int[]{android.R.attr.state_selected};
        states[3] = new int[]{android.R.attr.state_enabled};

        setDefaultColors();
        setTextColor();
        setIcon();
    }

    private void setDefaultColors() {
        if (mTextColorUnable == 0)
            mTextColorUnable = mTextColor;
        if (mTextColorChecked == 0)
            mTextColorChecked = mTextColor;
        if (mTextColorSelected == 0)
            mTextColorSelected = mTextColor;
    }

    private void setTextColor() {
        int[] colors = new int[]{mTextColorUnable, mTextColorChecked, mTextColorSelected, mTextColor};
        ColorStateList mTextColorStateList = new ColorStateList(states, colors);
        mView.setTextColor(mTextColorStateList);
    }

    private void setIcon() {
        if (mIconWidth == 0 && mIconHeight == 0) {
            if (mIcon != null) {
                mIconWidth = mIcon.getIntrinsicWidth();
                mIconHeight = mIcon.getIntrinsicHeight();
            }
        }
        /*setCompoundDrawables(mIcon, mIconWidth, mIconHeight, mIconDirection);*/
        StateListDrawable stateListDrawable = new StateListDrawable();
        stateListDrawable.addState(new int[]{-android.R.attr.state_enabled}, mIconUnable);
        stateListDrawable.addState(new int[]{android.R.attr.state_checked}, mIconChecked);
        stateListDrawable.addState(new int[]{android.R.attr.state_selected}, mIconSelected);
        stateListDrawable.addState(new int[]{android.R.attr.state_enabled}, mIcon);
        setCompoundDrawables(stateListDrawable, mIconWidth, mIconHeight, mIconDirection);
    }

    public void drawIconWithText() {
        if (!mDrawableWithText || mView == null || mView.getWidth() == 0)
            return;
        int drawablePadding = mView.getCompoundDrawablePadding();
        int drawableWidth = mIconWidth;
        int drawableHeight = mIconHeight;
        int drawablePaddingHorizontal = drawablePadding; // 水平方向间距
        int drawablePaddingVertical = drawablePadding; // 垂直方向间距
        if (mIconDirection == ICON_LEFT || mIconDirection == ICON_RIGHT) {
            drawableHeight = 0;
            drawablePaddingVertical = 0;
        }
        if (mIconDirection == ICON_TOP || mIconDirection == ICON_BOTTOM) {
            drawableWidth = 0;
            drawablePaddingHorizontal = 0;
        }
        // 水平方向
        float textWidth = TextViewUtil.get().getTextWidth(mView, drawableWidth, paddingLeft, paddingRight, drawablePaddingHorizontal);
        float bodyWidth = textWidth + drawableWidth + drawablePaddingHorizontal;
        float actualWidth = mView.getWidth() - (paddingLeft + paddingRight);
        int translateX = (int) ((actualWidth - bodyWidth) / 2); // 两边可用
        if (translateX < 0) translateX = 0;
        // 垂直方向计算
        float textHeight = TextViewUtil.get().getTextHeight(mView, drawableHeight, paddingTop, paddingBottom, drawablePaddingVertical);
        float bodyHeight = textHeight + drawableHeight + drawablePaddingVertical;
        float actualHeight = mView.getHeight() - (paddingTop + paddingBottom);
        int translateY = (int) ((actualHeight - bodyHeight) / 2);
        if (translateY < 0) translateY = 0;

        String paddingStr = new StringBuilder().append(mView.getWidth()).append(mView.getHeight())
                .append(translateX).append(paddingLeft)
                .append(translateY).append(paddingTop)
                .append(translateX).append(paddingRight)
                .append(translateY).append(paddingBottom).toString();
        if (!paddingStr.equals(mCacheSingleIconPaddingVale)) {
            mCacheSingleIconPaddingVale = paddingStr;
            // 设置padding会调用invalidate()
            mView.setPadding(translateX + paddingLeft, translateY + paddingTop, translateX + paddingRight, translateY + paddingBottom);
        }
    }

    private void setCompoundDrawables(Drawable drawable, int drawableWidth, int drawableHeight, int direction) {
        if (drawable != null) {
            drawable.setBounds(0, 0, drawableWidth, drawableHeight);
        }
        Drawable[] drawables = mView.getCompoundDrawables();
        Drawable leftDrawable = direction == ICON_LEFT ? drawable : (drawables != null ? drawables[0] : null);
        Drawable topDrawable = direction == ICON_TOP ? drawable : (drawables != null ? drawables[1] : null);
        Drawable rightDrawable = direction == ICON_RIGHT ? drawable : (drawables != null ? drawables[2] : null);
        Drawable bottomDrawable = direction == ICON_BOTTOM ? drawable : (drawables != null ? drawables[3] : null);
        if (drawable != null)
            mView.setCompoundDrawables(leftDrawable, topDrawable, rightDrawable, bottomDrawable);
    }

    public void setEnabled(boolean enabled) {
        /*if (enabled) {
            if (mIconNormal != null) {
                mIcon = mIconNormal;
                setIcon();
            }
        } else {
            if (mIconUnable != null) {
                mIcon = mIconUnable;
                setIcon();
            }
        }*/
    }

    public void setSelected(boolean selected) {
        if (!mView.isEnabled()) return;
        if (selected) {
            if (mIconSelected != null) {
                mIcon = mIconSelected;
                setIcon();
            }
        } else {
            if (mIconNormal != null) {
                mIcon = mIconNormal;
                setIcon();
            }
        }
    }

    public void setChecked(boolean checked) {
        /*if (!mView.isEnabled()) return;
        if (checked) {
            if (mIconChecked != null) {
                mIcon = mIconChecked;
                setIcon();
            }
        } else {
            if (mIconNormal != null) {
                mIcon = mIconNormal;
                setIcon();
            }
        }*/
    }

    /**
     * 设置文本默认颜色
     *
     * @param color
     * @return
     */
    public STextViewHelper setTextColor(int color) {
        this.mTextColor = color;
        setDefaultColors();
        setTextColor();
        return this;
    }

    /**
     * 设置文本选中时颜色
     *
     * @param color
     * @return
     */
    public STextViewHelper setSelectTextColor(int color) {
        this.mTextColorSelected = color;
        setDefaultColors();
        setTextColor();
        return this;
    }

    public STextViewHelper setCheckTextColor(int color) {
        this.mTextColorChecked = color;
        setDefaultColors();
        setTextColor();
        return this;
    }

    /**
     * 设置文本unable时颜色
     *
     * @param color
     * @return
     */
    public STextViewHelper setUnableTextColor(int color) {
        this.mTextColorUnable = color;
        setDefaultColors();
        setTextColor();
        return this;
    }

    /**
     * 按钮选中状态
     *
     * @return
     */
    protected boolean isCompoundButtonChecked() {
        return false;
    }
}
